import sys
import os
import datetime
from google.appengine.api import mail
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from models.invoice              import Invoice
from models.company              import Company
from models.backup               import Backup
from models.personal             import Personal

class ToolsService():
	class Index(webapp.RequestHandler):
		def get(self):
			path = os.path.join(os.path.dirname(__file__), '../views/tools/index.html')
			html = template.render(path, {})
			self.response.out.write(html)
	
	class ComputeTax(webapp.RequestHandler):
		def get(self):
			startDate        = datetime.datetime.strptime(self.request.get('startDate'), "%Y-%m-%d")
			endDate          = datetime.datetime.strptime(self.request.get('endDate'), "%Y-%m-%d")
			invoices         = []
			total_amount     = 0
			total_amount_gst = 0
			for n in Invoice.get_range(startDate, endDate):
				total_amount     += (n.rate * n.hours)
				total_amount_gst += (n.rate * n.hours) + ((n.rate * n.hours) * n.taxRate)
				invoices.append({
					'company'   : n.company,
					'number'    : n.number,
					'startDate' : n.startDate,
					'endDate'   : n.endDate,
					'amount'    : (n.rate * n.hours),
					'amountGST' : (n.rate * n.hours) + ((n.rate * n.hours) * n.taxRate)
				})
				
			path = os.path.join(os.path.dirname(__file__), '../views/tools/compute-tax-result.html')
			html = template.render(path, {'invoices'         : invoices,
										  'startDate'        : startDate,
										  'endDate'          : endDate,
										  'total_amount'     : total_amount,
										  'total_amount_gst' : total_amount_gst,
										  'total_gst'        : total_amount_gst - total_amount})
			self.response.out.write(html)
			
	class AppData(webapp.RequestHandler):
		def get(self):
			self.response.out.write( Backup.export() )
		def post(self):
			try:
				result = Backup.load(str(self.request.get('data')))
				self.response.out.write('companies created : ' + str(result['company_create']) + '\n')
				self.response.out.write('companies updated : ' + str(result['company_update']) + '\n')	
				self.response.out.write('invoices  created : ' + str(result['invoice_create']) + '\n')	
				self.response.out.write('invoices  updated : ' + str(result['invoice_update']) + '\n')
			except:
				exc_type, exc_value, exc_traceback = sys.exc_info()
				self.response.out.write(exc_value)
				
	class EmailBackup(webapp.RequestHandler):
		def get(self):
			personal = Personal().get()
			
			mail.send_mail(sender=personal.email,
							to=personal.email,
							subject="Invoice Backup",
							body=Backup.export())		
			self.response.out.write('back up sent')